<template>
    <div class="user-loan-in-detail-me" v-if='pageLoaded'>
        <!-- wrapper -->
        <div class="wrapper">
            <div class="loan-detail-header">
                <div class="loan-detail-number">
                    <p class="loan-detail-number__number">编号: {{number}}</p>
                    <span class="loan-detail-number__status orange">{{ detail.repayStateStr }}</span>
                </div>
                <div class="loan-detail-user" v-if='loanUserInfo.user'>
                    <span class="loan-detail-user__avatar"><img :src="loanUserInfo.user.avatar || placeholderImg" alt=""></span>
                    <div class="loan-detail-user__info">
                        <p class='name'>{{loanUserInfo.user.realName}}</p>
                        <p>借款人</p>
                    </div>
                    <span class="button short transparent" @click='goReportDetail'>信用报告</span>
                </div>
                <div class="loan-detail-money">
                    <div class="loan-detail-money__total">
                        <p class='text'>借款总额</p>
                        <span class='number'>{{detail.borrowAmount | toYuan}}元</span>
                    </div>
                    <div class="loan-detail-money__total-true">
                        <p>实际到账<span>{{detail.borrowReceiveAmount | toYuan}}元</span></p>
                        <small>已扣除手续费{{detail.commissionFee | toYuan}}元,服务费{{detail.serviceFee | toYuan}}元</small>
                    </div>
                    <ul class="loan-detail-money__list">
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.yearRate/100}}%</span>
                            <p>年化利率</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.borrowDays}}{{detail.daysTypeStr}}</span>
                            <p>借款时长</p>
                        </li>
                        <li class="loan-detail-money__item">
                            <span class='persent'>{{detail.interestAmount | toYuan}}</span>
                            <p>预计利息(元)</p>
                        </li>
                    </ul>
                </div>

                <div class="loan-detail-content">
                    <div class="loan-detail-agreement">
                        <span class='button short pure' 
                            @click='showAgreement = true' 
                            v-if='detail.repayState != "SYSTEM_FREEZE"'>查看借款协议</span>
                        <p class="detail-button" :class="{ 'active':showDetail }" @click='showDetail = !showDetail'>展开借款详情</p>
                    </div>
                    <div class="loan-detail-info" v-show='showDetail'>
                        <ul class="card__info">
                            <li class="card__info-item">借款日期：{{ detail.createdAt | dateFormat  }}</li>
                            <li class="card__info-item">还款方式：{{detail.repayWayStr}}</li>
                            <li class="card__info-item">借款用途：{{ detail.borrowUsage  }}</li>
                        </ul>
                        <!-- <p class="card__info-item full">补充说明: {{ detail.addSay || placeholder  }}</p> -->
                        <template v-if='detail.imageSay && detail.imageSay.length'>
                            <div class="card__info-item">图片说明：</div>
                            <ul class="loan-detail-info__pics">
                                <li class="loan-detail-info__pic" v-for='item in detail.imageSay' @click='imgViewShow(item.url)'>
                                    <img :src="item.url">
                                </li>
                            </ul>
                        </template>
                    </div>
                </div>
            </div>
            <div class="loan-detail-message" v-if='messageList.length'>
                <div class="loan-detail-message__box" @click='goMessageDetail'>
                    <slide
                        swiperId='loanIOUMessage'
                        direction='vertical'
                        :autoplay='2000'>
                        <div v-for='item in messageList' :data-index='index' :data-id='item.messageId'>
                            {{item.content}}
                        </div>
                    </slide>
                </div>
            </div>

            <div class="loan-detail-repayment">
                <div class="repayment-tab" :class='{purple : isPub}'>
                    <div class="repayment-tab__item" @click='tabIndex = 0' :class="{'active':tabIndex == 0}">
                        <p class='title' v-if='isPub'>收款计划({{repayPlanAll.length}})</p>
                        <p class='title' v-else>还款计划({{repayPlanAll.length}})</p>
                        <p class='money' v-if='isPub'>{{repayText}} {{detail.waiteReceiveAmount | toYuan}}</p>
                        <p class='money' v-else>{{repayText}} {{detail.waiteRepayAmount | toYuan}}</p>
                    </div>
                    <div class="repayment-tab__item" @click='tabIndex = 1' :class="{'active':tabIndex == 1}">
                        <p class='title' v-if='isPub'>收款记录({{repayPlanRepaid.length}})</p>
                        <p class='title' v-else>还款记录({{repayPlanRepaid.length}})</p>
                        <p class='money' v-if='isPub'>{{repaidText}}  {{detail.receivedAmount | toYuan}}</p>
                        <p class='money' v-else>{{repaidText}}  {{detail.repaidAmount | toYuan}}</p>
                    </div>
                </div>
                <div class="repayment-detail" v-show='tabIndex == 0'>
                    <template v-if='repayPlanAll.length'>
                        <div class="repayment-detail__item head">
                            <span class="repayment-detail__value">期数</span>
                            <span class="repayment-detail__value" v-if='isPub'>收款日</span>
                            <span class="repayment-detail__value" v-else>还款日</span>
                            <span class="repayment-detail__value">金额</span>
                            <span class="repayment-detail__value">状态</span>
                        </div>
                        <ul>
                            <li class="repayment-detail__item" v-for='item in repayPlanAll' @click='setRepayInfo(item)' >
                                <span class="repayment-detail__value">第{{item.currentPeriod || placeholder}}期</span>
                                <span class="repayment-detail__value">{{item.shouldRepayDate | dateFormat}}</span>
                                <span class="repayment-detail__value" v-if='isPub'>{{item.receiveAmount | toYuan}}</span>
                                <span class="repayment-detail__value" v-else>{{item.repayAmount | toYuan}}</span>
                                <div class="repayment-detail__value"> 
                                    <span>{{item.repaid | repayState(detail,item)}}</span> 
                                    <!-- <span v-if='!item.repaid'>{{item.overdue | overdueState}}</span> -->
                                </div>
                            </li>
                        </ul>
                    </template>
                    <p class="page-placeholder" v-if='!repayPlanAll.length && isPub'>
                        <span v-if='detail.repayState == "SYSTEM_FREEZE"'>冻结中，暂无法查看</span>
                        <span v-else>暂无收款记录</span>
                    </p>
                    <p class="page-placeholder" v-if='!repayPlanAll.length && !isPub'>
                        <span v-if='detail.repayState == "SYSTEM_FREEZE"'>冻结中，暂无法查看</span>
                        <span v-else>暂无还款记录</span>
                    </p>
                </div>
                <div class="repayment-detail" v-show='tabIndex == 1'>
                    <template v-if='repayPlanRepaid.length'>
                        <div class="repayment-detail__item head">
                            <span class="repayment-detail__value">期数</span>
                            <span class="repayment-detail__value" v-if='isPub'>收款日</span>
                            <span class="repayment-detail__value" v-else>还款日</span>
                            <span class="repayment-detail__value">金额</span>
                            <span class="repayment-detail__value">状态</span>
                        </div>
                        <ul>
                            <li class="repayment-detail__item" v-for='item in repayPlanRepaid' @click='setRepayInfo(item)' >
                                <span class="repayment-detail__value">第{{item.currentPeriod || placeholder}}期</span>
                                <span class="repayment-detail__value">{{item.shouldRepayDate | dateFormat}}</span>
                                <span class="repayment-detail__value" v-if='isPub'>{{item.receiveAmount | toYuan}}</span>
                                <span class="repayment-detail__value" v-else>{{item.repayAmount | toYuan}}</span>
                                <span class="repayment-detail__value">已还清</span>
                            </li>
                        </ul>
                    </template>
                    <p class="page-placeholder" v-if='!repayPlanRepaid.length && isPub'>
                        <span v-if='detail.repayState == "SYSTEM_FREEZE"'>冻结中，暂无法查看</span>
                        <span v-else>暂无收款记录</span>
                    </p>
                    <p class="page-placeholder" v-if='!repayPlanRepaid.length && !isPub'>
                        <span v-if='detail.repayState == "SYSTEM_FREEZE"'>冻结中，暂无法查看</span>
                        <span v-else>暂无还款记录</span>
                    </p>
                </div>
            </div>
        </div>
            
        <!-- footer -->
        <div 
            class="single-button" 
            @click='showRepaymentList = true' 
            v-if='(detail.isMyApplyBorrow || detail.isMyPublishBorrow) && detail.repayState != "REPAID" && detail.repayState != "SYSTEM_FREEZE"'>
            <span class="button">立即还款</span>
        </div>
        <div class="single-button" @click='showUser = true' v-if='detail.isOverdue && (detail.isApplyToMyLend || detail.isMyPublishLend)'>
            <span class="button purple">立即催收</span>
        </div>
        <modal 
            :show='show_modal_loan_detail'
            @close='show_modal_loan_detail = false'>
            <div class='modal-repayment-detail'>
                <div class="modal-repayment-detail__header">
                    <div class='modal-repayment-detail__period'>
                        <p class="period">第{{ currentRepayInfo.currentPeriod }}期</p>
                        <p class="time">{{currentRepayInfo.shouldRepayDate | dateFormat}}(请于22:00前还款)</p>
                    </div>
                    <p class='modal-repayment-detail__money'>{{currentRepayInfo.repayAmount | toYuan}}</p>
                </div>
                <ul class="modal-repayment-detail__main">
                    <li class="modal-repayment-detail__item">
                        <p class="key">本金</p>
                        <p class="value">{{currentRepayInfo.principalAmount | toYuan}}</p>
                    </li>
                    <li class="modal-repayment-detail__item">
                        <p class="key">利息</p>
                        <p class="value">{{currentRepayInfo.interestAmount | toYuan}}</p>
                    </li>
                    <li class="modal-repayment-detail__item">
                        <p class="key">罚息</p>
                        <p class="value">{{currentRepayInfo.overdueAmount | toYuan}}</p>
                    </li>
                    <li class="modal-repayment-detail__item">
                        <p class="key">逾期管理费*</p>
                        <p class="value">{{currentRepayInfo.overdueMgrAmount | toYuan}}</p>
                    </li>
                </ul>
                <p class="modal-repayment-detail__tips">*由平台收取，不计入待收。如符合奖励规则，出借人将收到相应比例的奖励</p>
            </div>
        </modal>

        <agreement
            v-if='detail'
            :no='detail.borrowNo'
            :show='showAgreement'
            @close='showAgreement=false'></agreement>

        <image-view 
            :url='currentImg' 
            :show='modal_img_show' 
            @close='modal_img_show = false'></image-view>
        
        <repayment-list 
            v-if='repayList.length'
            :show='showRepaymentList'
            v-model='repayList'
            @close='showRepaymentList=false'
            @finish='repaymentListFinish'></repayment-list>
        
        <user
            v-if='loanUserInfo.creditReport'
            :number='loanUserInfo.creditReport.creditReportNo'
            :show='showUser'
            @close='showUser=false'></user>

        <pay-detail
            :amount='repayTotalAmount'
            :show='showPayDetail'
            @close='showPayDetail=false'
            @finish='payDetailFinish'></pay-detail>

        <pay-password
            :show='showPayPassword'
            @close='showPayPassword=false'
            @finish='payFinish'></pay-password>

        <sms-code
            v-if='userInfo'
            type='REPAY_PLAN'
            :show='showSmsCode'
            :mobile='userInfo.user.mobile'
            @close='showSmsCode=false'
            @finish='smsFinish'></sms-code>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import countDown from '../components/CountDown.vue'
    import repaymentList from '../components/RepaymentList.vue'
    import payPassword from '../components/PayPassword.vue'
    import payDetail from '../components/PayDetail.vue'
    import smsCode from '../components/SmsCode.vue'
    import toYuan from '../filters/filter-toYuan'
    import imageView from '../components/ImageView.vue'
    import slide from '../components/Slide.vue'
    import user from '../components/User.vue'
    import dateFormat from '../filters/filter-dateFormat'
    import agreement from '../components/Agreement.vue'
    import  { mapGetters, mapActions }  from 'vuex'
    import { loanInApi, loanOutApi, userApi, payApi, messageApi } from '../api/api'
    import { getQueryString } from '../utils/utils'
    import moment from 'moment'

    export default {
        components:{
            modal,
            slide,
            confirm,
            countDown,
            imageView,
            repaymentList,
            payPassword,
            payDetail,
            agreement,
            smsCode,
            user
        },
        filters:{
            toYuan,
            dateFormat,
            repayState(repay,detail,item){
                let now = moment()
                let time = moment(item.shouldRepayDate)
                let diffDays

                diffDays = Math.ceil(time.diff(now,'days',true))
                if(diffDays < 0){
                    diffDays -- 
                }

                if(detail.isMyPublishLend || detail.isApplyToMyLend){
                    if(repay) return '已收'
                    if(!repay && item.overdue) return `逾期${item.overdueDays}天`
                    if(!repay && !item.overdue) return '待收'
                }
                if(repay) return '已还清'
                if(!repay && item.overdue) return `逾期${item.overdueDays}天`
                if(!repay && !item.overdue) return '待还'
            },
        },
        data() {
            return {
                placeholderImg:require('../images/loading_1.png'),
                placeholder:'--',
                showDetail:false,
                showUser:false,
                showAgreement:false,
                showRepaymentList:false,
                messageList:[],
                repayPlanAll:[],
                repayList:[],
                repayPlanRepaid:[],
                currentRepayInfo:{},
                pageLoaded:false,
                number:this.$route.params.number,
                passwordPass:false,
                payWay:'',
                showPayPassword:false,
                showPayDetail:false,
                showSmsCode:false,
                modal_img_show:false,
                show_modal_reject_apply:false,
                smsCode:'',
                currentImg:'',
                detail:'',
                loanUserInfo:{},
                tabIndex:0,
                show_modal_loan_detail:false
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo'
            ]),
            userInfo(){
                return this.localInfo.userInfo
            },
            isPub(){
                if(!_.isEmpty(this.detail)){
                    return this.detail.isApplyToMyLend || this.detail.isMyPublishLend
                }
            },
            repayPlanIds(){
                let ids = ''
                _.each(this.repayList,(value,index)=>{
                    if(value.check == true){
                        ids ? ids = `${ids},${value.repayPlanId}` : ids = `${value.repayPlanId}`
                    }
                })
                return ids            
            },
            repayTotalAmount(){
                let amount = 0
                _.each(this.repayList,(value,index)=>{
                    if(value.check == true){
                        amount = amount + value.repayAmount
                    }
                })
                return amount            
            },
            repayText(){
                if(this.isPub){
                    return '剩余待收'
                }
                return '剩余待还'
            },
            repaidText(){
                if(this.isPub){
                    return '已收款'
                }
                return '已还款'
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip'
            ]),

            // filters
            timestampToDate(timestamp){
                if(!timestamp) return this.placeholder
                return moment(timestamp).format('YYYY-MM-DD')
            },

            // function

            goRouter(name){
                this.$router.push({
                    name:name
                })
            },
            setRepayInfo(info){
                this.currentRepayInfo = info
                this.show_modal_loan_detail = true
            },
            goReportDetail(){
                if(!this.loanUserInfo.creditReport){
                    this.setMsgTip({
                        text:'该用户暂无信用报告！',
                        type:'warn'
                    })
                    return
                }

                this.$router.push({
                    name:'user-credit-report-detail',
                    params:{
                        no:this.loanUserInfo.creditReport.creditReportNo
                    }
                })
            },
            imgViewShow(url){
                this.currentImg = url
                this.modal_img_show = true
            },
            confirm(){
                this.showPayDetail = true
            },
            goRepayment(){
                this.$router.push({
                    name:'repayment',
                    params:{
                        no:this.number
                    }
                })
            },
            goSuccess(){
                this.$router.push({
                    name:'loan-in-success'
                })
            },
            repaymentListFinish(){
                this.showRepaymentList = false
                this.showPayDetail = true
            },
            payDetailFinish(payObject){
                if(payObject.payType == 0){
                    this.payWay = 'CHARGE'
                }
                else{
                    this.payWay = 'BALANCE'
                }
                this.showPayDetail = false

                // if(this.passwordPass) {
                //     this.showSmsCode = true
                // }
                // else {
                    this.showPayPassword = true
                // }
            },
            payFinish(password){
                this.password = password
                this.passwordPass = true
                this.showPayPassword = false
                if(this.payWay == 'BALANCE'){
                    this.showSmsCode = true
                }
                else{
                    this.repay()
                }
            },
            smsFinish(smsCode){
                this.smsCode = smsCode
                this.showSmsCode = false
                this.repay()
            },
            getDetail(){
                return loanInApi.detail({
                    borrowNo:this.number
                })
                .then(result=>{
                    if(!_.isEmpty(result.repayPlanAll)){
                        _.each(result.repayPlanAll,(value,index)=>{
                            value.check = false
                        })
                    }
                    this.detail = result
                    this.repayPlanAll = result.repayPlanAll || []
                    this.repayList = _.filter(result.repayPlanAll,(value,index)=>{
                        return value.repaid == false
                    })
                    this.repayPlanRepaid = result.repayPlanRepaid || []
                    this.hideLoading()
                })
            },
            getUserInfo(){
                return loanInApi.userInfo({
                    borrowNo:this.number
                })
                .then(result=>{
                    this.loanUserInfo = result
                })
            },
            repay(){
                this.showLoading()
                let params = {
                    payWay:this.payWay,
                    tradePassword:this.password,
                    smsCode:this.smsCode,
                    repayPlanId:this.repayPlanIds,
                }
                userApi.repayPlan(params)
                .then(result=> {
                    if(_.isEmpty(result)){
                        this.setMsgTip({
                            text:'还款成功',
                            type:'success'
                        })
                        this.getDetail()
                        this.getMessage()
                        // this.$router.replace({
                        //     name:'user-index'
                        // })
                        return
                    }
                    this.payId = result.charge.payId
                    this.pay()
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
            pay(){
                payApi.pay({
                    payId:this.payId,
                    returnUrl:location.href
                })
                .then(result=> {
                    location.href = result.payParam.url
                })
                .catch(error=> {
                    console.error(error);
                    this.hideLoading()
                })
            },
            goMessageDetail(event){
                let el = $(event.target).closest('.swiper-slide')
                if(!el.length) return

                let id = el.data('id')

                this.$router.push({
                    name:'message-box-detail',
                    params:{
                        id:id
                    }
                })
            },
            getMessage(){
                messageApi.typeList({
                    type:"OVERDUE",
                    outerId:this.number
                })
                .then(result=> {
                    this.messageList = result
                    // this.hideLoading()
                })
                .catch(error=> {
                    console.log(error);
                    // this.hideLoading()
                })

            }
        },
        created(){

            let status = this.$route.query.status
            if(status == 'fail'){
                this.setMsgTip({
                    text:'还款失败！',
                    type:'error'
                })
            }
            if(status == 'success'){
                this.setMsgTip({
                    text:'还款成功！',
                    type:'success'
                })
            }
            Promise.all([this.getUserInfo(), this.getDetail()])
            .then(result=> {
                this.pageLoaded = true
                this.hideLoading()
            })
            .catch(error=> {
                console.error(error);
                this.pageLoaded = true
                this.hideLoading()
            })
            this.getMessage()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .user-loan-in-detail-me{
        .wrapper{
            padding-bottom: 100px;
        }
        .loan-detail-main{
            background-color: #fff;
            margin-top: 52px;
            padding:0 24px;
            position: relative;
        }
        .loan-detail-repayment{
            padding-top: 16px;
        }
        .repayment-tab{
            display: flex;
            background-color: #fff;
            &.purple{
                .repayment-tab__item{
                    &:after{
                        border-top:2px solid $purple;
                    }
                }
            }
        }
        .repayment-tab__item{
            flex:1;
            text-align: center;
            padding:10px 0 8px 0;
            position: relative;
            &:after{
                content:'';
                transition:ease 150ms transform;
                transform:scale(0);
                border-top:2px solid $orange;
                position: absolute;
                bottom:0;
                left:16px;
                right:16px;
            }
            &:active,&.active{
                &:after{
                    transform:scale(1);
                }
            }
            .title{
                @extend %font-title;
                color:$importColor;
            }
            .money{
                @extend %font-caption;
            }
        }
        .repayment-detail{
            text-align: center;
        }
        .repayment-detail__item{
            @extend %font-caption;
            color:$importColor;
            background-color: #fff;
            &.head{
                color:$defaultColor;
                font-weight: 400;
                background-color: transparent;
            }
            display: flex;
            padding: 0 24px;
            border-top:1px solid $sectionColor;
        }
        .repayment-detail__value{
            display: block;
            width: 20%;
            flex:1;
            box-sizing:border-box;
            padding: 14px 0 14px 0;
            &:first-child{
                padding-left: 0;
            }
        }
        .modal-repayment-detail{

        }
        .modal-repayment-detail__header{
            display: flex;
            justify-content: space-between;
            padding-bottom: 8px;
            border-bottom: 1px solid $sectionColor;
        }
        .modal-repayment-detail__period{
            .period{
                @extend %font-body1;
                color:$importColor;
            }
            .time{
                @extend %font-caption;
            }
        }
        .modal-repayment-detail__money{
                @extend %font-title;
                color:$importColor;
        }
        .modal-repayment-detail__main{
            padding-top: 8px;
            padding-bottom: 16px;
            border-bottom:1px solid $sectionColor;
        }
        .modal-repayment-detail__tips{
            @extend %font-caption;
            padding-top: 16px;
        }
        .modal-repayment-detail__item{
            padding-top: 8px;
            display: flex;
            justify-content: space-between;
            .key{
                @extend %font-body1;
            }
            .value{
                @extend %font-caption;
                color:$importColor;
            }
        }
    }

</style>
